<?php
/**
 * 商家中心-砍价
 *
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */

use Shopnc\Tpl;


defined('InShopNC') or exit('Access Invalid!');

class store_promotion_kanjiaControl extends BaseSellerControl
{

    const LINK_LIST = 'index.php?act=store_promotion_kanjia&op=index';
    const LINK_MANAGE = 'index.php?act=store_promotion_kanjia&op=kanjia_manage&kanjia_id=';

    const KANJIA_STATE_UNREVIEWED   = 0;    //默认：未审核
    const KANJIA_STATE_PASS         = 1;    //通过
    const KANJIA_STATE_FAIL         = 2;    //未通过
    const KANJIA_STATE_REAPPLY      = 3;    //再次申请
    const KANJIA_STATE_CLOSE        = 4;    //活动关闭
    const KANJIA_STATE_DELETE_ADMIN = 5;    //管理员删除
    const KANJIA_STATE_SOFT_DELETE  = 6;    //软删除

    private $mansong_state_array = array(
        self::KANJIA_STATE_UNREVIEWED   => '未审核',
        self::KANJIA_STATE_PASS         => '通过',
        self::KANJIA_STATE_FAIL         => '未通过',
        self::KANJIA_STATE_REAPPLY      => '再次申请',
        self::KANJIA_STATE_CLOSE        => '活动关闭',
        self::KANJIA_STATE_DELETE_ADMIN => '管理员删除',
        self::KANJIA_STATE_SOFT_DELETE  => '删除'
    );

    public function __construct()
    {
        parent::__construct();
        $model_kanjia = Model('p_kanjia');
        $model_kanjia->getStateArray();
    }
    /**
     * 得到操作类型
     * @return array
     */
    public function getMansongStateArray()
    {
        return $this->mansong_state_array;
    }

    public function indexOp()
    {
        $model_kanjia = Model('p_kanjia');

        if (checkPlatformStore()) {
            Tpl::output('isOwnShop', true);
        } else {
            $current_quota = $model_kanjia->getQuotaCurrent($_SESSION['store_id']);
            Tpl::output('current_quota', $current_quota);
        }

        $condition             = array();
        $condition['store_id'] = $_SESSION['store_id'];
        if (!empty($_GET['name'])) {
            $condition['kanjia_name'] = array('like', '%' . $_GET['name'] . '%');
        }
        $kanjia_list = $model_kanjia->getList($condition, 10);
        Tpl::output('list', $kanjia_list);
        Tpl::output('show_page', $model_kanjia->showpage());
//
        self::profile_menu('kanjia_list');
        Tpl::showpage('store_promotion_kanjia.list');
    }

    /**
     * 添加活动
     **/
    public function kanjia_addOp()
    {
        if (checkPlatformStore()) {
            Tpl::output('isOwnShop', true);
        } else {
            $model_kanjia   = Model('p_kanjia');
            $current_kanjia = $model_kanjia->getQuotaCurrent($_SESSION['store_id']);
            if (empty($current_kanjia)) {
                showMessage(Language::get('kanjia_current_error1'), '', '', 'error');
            }
            Tpl::output('current_kanjia_quota', $current_kanjia);
        }

        //输出导航
        self::profile_menu('kanjia_add');
        Tpl::showpage('store_promotion_kanjia.add');

    }

    /**
     * 保存添加的活动
     **/
    public function kanjia_saveOp()
    {
        $model_kanjia = Model('p_kanjia');
        //验证输入
        $kanjia_name = trim($_POST['kanjia_name']);
        $start_time  = strtotime($_POST['start_time']);
        $end_time    = strtotime($_POST['end_time']);
        $min_num     = intval($_POST['min_num']);
        if ($min_num <= 1) {
            $min_num = 2;
        }
        if (!checkPlatformStore()) {
            $current_kanjia = $model_kanjia->getQuotaCurrent($_SESSION['store_id']);
            if (empty($current_kanjia)) {
                showDialog('没有可用套餐,请先购买套餐');
            }
            $quota_start_time = intval($current_kanjia['start_time']);
            $quota_end_time   = intval($current_kanjia['end_time']);
            if ($start_time < $quota_start_time) {
                showDialog(sprintf('开始时间不能为空且不能早于%s', date('Y-m-d', $current_kanjia['start_time'])));
            }
            if ($end_time > $quota_end_time) {
                showDialog(sprintf('结束时间不能为空且不能晚于%s', date('Y-m-d', $current_kanjia['end_time'])));
            }
        }
        $param                   = array();
        $param['kanjia_name']    = $kanjia_name;
        $param['kanjia_title']   = $_POST['kanjia_title'];
        $param['kanjia_explain'] = $_POST['kanjia_explain'];
        $param['quota_id']       = $current_kanjia['quota_id'] ? $current_kanjia['quota_id'] : 0;
        $param['start_time']     = $start_time;
        $param['end_time']       = $end_time;
        $param['store_id']       = $_SESSION['store_id'];
        $param['store_name']     = $_SESSION['store_name'];
        $param['member_id']      = $_SESSION['member_id'];
        $param['member_name']    = $_SESSION['member_name'];
        $param['min_num']        = $min_num;
        $result                  = $model_kanjia->add($param);
        if ($result) {
            $this->recordSellerLog('添加砍价活动，活动名称：' . $kanjia_name . '，活动编号：' . $result);
            showDialog(Language::get('nc_common_save_succ'), self::LINK_MANAGE . $result, 'succ', '', 3);
        } else {
            showDialog(Language::get('nc_common_save_fail'));
        }
    }

    /**
     * 编辑活动
     **/
    public function kanjia_editOp()
    {
        $model_kanjia           = Model('p_kanjia');
        $kanjia_id              = intval($_GET['kanjia_id']);
        $condition              = array();
        $condition['store_id']  = $_SESSION['store_id'];
        $condition['kanjia_id'] = $kanjia_id;
        $kanjia_info            = $model_kanjia->getInfo($condition);
        if (empty($kanjia_info)) {
            showMessage('参数错误', '', '', 'error');
        }

        Tpl::output('kanjia_info', $kanjia_info);

        //输出导航
        self::profile_menu('kanjia_edit');
        Tpl::showpage('store_promotion_kanjia.add');
    }

    /**
     * 编辑保存活动
     **/
    public function kanjia_edit_saveOp()
    {
        $model_kanjia           = Model('p_kanjia');
        $kanjia_id              = intval($_POST['kanjia_id']);
        $condition              = array();
        $condition['store_id']  = $_SESSION['store_id'];
        $condition['kanjia_id'] = $kanjia_id;
        $kanjia_info            = $model_kanjia->getInfo($condition);
        if (empty($kanjia_info)) {
            showDialog(Language::get('param_error'));
        }

        //验证输入
        $kanjia_name = trim($_POST['kanjia_name']);
        $min_num     = intval($_POST['min_num']);
        if ($min_num <= 1) {
            $min_num = 2;
        }

        //生成活动
        $param                   = array();
        $param['kanjia_name']    = $kanjia_name;
        $param['kanjia_title']   = $_POST['kanjia_title'];
        $param['kanjia_explain'] = $_POST['kanjia_explain'];
        $param['min_num']        = $min_num;
        $result                  = $model_kanjia->edit($param, array('kanjia_id' => $kanjia_id));
        if ($result) {
            $model_kanjia->editGoods($param, array('kanjia_id' => $kanjia_id));
            $this->recordSellerLog('编辑砍价活动，活动名称：' . $kanjia_name . '，活动编号：' . $kanjia_id);
            showDialog(Language::get('nc_common_op_succ'), self::LINK_LIST, 'succ', '', 3);
        } else {
            showDialog(Language::get('nc_common_op_fail'));
        }
    }

    /**
     * 活动删除
     **/
    public function kanjia_delOp()
    {
        $kanjia_id = intval($_POST['kanjia_id']);

        $model_kanjia = Model('p_kanjia');

        $data           = array();
        $data['result'] = true;

        $condition              = array();
        $condition['store_id']  = $_SESSION['store_id'];
        $condition['kanjia_id'] = $kanjia_id;
        $kanjia_info            = $model_kanjia->getInfo($condition);
        if (!$kanjia_info) {
            showDialog('参数错误');
        }

        $model_kanjia = Model('p_kanjia');
        $result       = $model_kanjia->del($condition);
        if ($result) {
            $this->recordSellerLog('删除砍价活动，活动名称：' . $kanjia_info['kanjia_name'] . '活动编号：' . $kanjia_id);
            showDialog(L('nc_common_op_succ'), urlShop('store_promotion_kanjia', 'kanjia_list'), 'succ');
        } else {
            showDialog(L('nc_common_op_fail'));
        }
    }

    /**
     * 活动管理（原本商家自己添加砍价活动）
     **/
    public function kanjia_manageOp()
    {
        $model_kanjia = Model('p_kanjia');

        $kanjia_id              = intval($_GET['kanjia_id']);
        $condition              = array();
        $condition['store_id']  = $_SESSION['store_id'];
        $condition['kanjia_id'] = $kanjia_id;
        $kanjia_info            = $model_kanjia->getInfo($condition);
        Tpl::output('kanjia_info', $kanjia_info);

        //获取商品列表
        $condition              = array();
        $condition['store_id']  = $_SESSION['store_id'];
        $condition['kanjia_id'] = $kanjia_id;
        $goods_list             = $model_kanjia->getGoodsList($condition, 10);
        Tpl::output('show_page', $model_kanjia->showpage());
        Tpl::output('kanjia_goods_list', $goods_list);

        //输出导航
        self::profile_menu('kanjia_manage');
        Tpl::showpage('store_promotion_kanjia.manage');
    }

    /**
     * Author   benald
     * 活动管理（后台管理员添加砍价活动，由商家申请活动）
     **/
    public function kanjia_manage_applyOp()
    {
        $model_kanjia          = Model('p_kanjia');
        $marketing_activity_id = intval($_GET['marketing_activity_id']);

        if ($marketing_activity_id <= 0) {
            showMessage(Language::get('para_error'), 'index.php?act=store_marketing_activity&op=store_marketing_activity', 'html', 'error');
        }
        $marketing_activity_model = Model('marketing_activity');
        $map                      = array(
            'marketing_activity.marketing_activity_id'    => $marketing_activity_id,
            'marketing_activity.marketing_activity_state' => $marketing_activity_model::ACTIVITY_OPEN,
            'marketing_activity.marketing_activity_show'  => $marketing_activity_model::ACTIVITY_SHOW
        );
        $activity_info            = $marketing_activity_model->getOneData($map);
        //活动类型必须是商品并且活动没有关闭并且活动进行中
        if (empty($activity_info) || $activity_info['marketing_activity_state'] != $marketing_activity_model::ACTIVITY_OPEN || $activity_info['marketing_activity_end_date'] < TIMESTAMP) {
            showMessage(Language::get('store_activity_not_exists'), 'index.php?act=store_marketing_activity&op=store_marketing_activity', 'html', 'error');
        }
        Tpl::output('activity_info', $activity_info);

        //查询商品分类列表
        $gc      = Model('goods_class');
        $gc_list = $gc->getTreeClassList(3);
        foreach ($gc_list as $k => $gc) {
            $gc_list[$k]['gc_name'] = '';
            $gc_list[$k]['gc_name'] = str_repeat("&nbsp;", $gc['deep'] * 2) . $gc['gc_name'];
        }
        Tpl::output('gc_list', $gc_list);
        //查询品牌列表
        $brand      = Model('brand');
        $brand_list = $brand->getBrandList(array());
        Tpl::output('brand_list', $brand_list);

        //确定操作对象
        $model_name = $marketing_activity_model->activityTypeShiftModel($activity_info['marketing_activity_type']);
        if (!$model_name) {
            return array();  //营销类型错误
        }
        $model_name = Model($model_name);

        //获取商品列表
        $condition              = array();
        $p_kanjia               = $model_kanjia->getInfo(array('marketing_activity_id' => $marketing_activity_id));
        $condition['p_kanjia_goods.kanjia_id'] = $p_kanjia['kanjia_id'];
        $condition['p_kanjia_goods.store_id']  = $_SESSION['store_id'];
        $activity_goods             = $model_kanjia->getGoodsListState($condition, 10);

        //是否显示报名
        $store_goods_limit = isset($activity_info['store_goods_limit']) ? (int)$activity_info['store_goods_limit'] : 0;     //活动商家报名限制
        $already_apply = $model_name->getActivityApplyGoodsCount($condition['kanjia_id'], $_SESSION['store_id']);    //商家已经报名该营销活动商品数量
        $if_show_apply = $activity_info['marketing_activity_apply_end_date'] < time() ? false : ($store_goods_limit==0 ? true : ($store_goods_limit > $already_apply) ? ($store_goods_limit - $already_apply) : false);     //若显示，返回剩余额度，否则返回false

        //输出导航
        Tpl::output('if_show_apply', $if_show_apply);
        Tpl::output('activity_goods', $activity_goods);
        Tpl::output('marketing_activity_id', $marketing_activity_id);
        Tpl::output('check_state_array',  $this->getMansongStateArray());
        Tpl::output('goods_state_array',  Model('goods')->getGoodsStateArray());
        /**
         * 页面输出
         */
        self::profile_menu('kanjia_manage_apply');
        Tpl::showpage('store_promotion_kanjia.apply');
    }


    /**
     * 套餐购买
     **/
    public function quota_addOp()
    {
        //输出导航
        self::profile_menu('kanjia_add');
        Tpl::showpage('store_promotion_kanjia_quota.add');
    }

    /**
     * 套餐购买保存
     **/
    public function quota_add_saveOp()
    {

        $kanjia_quantity = intval($_POST['kanjia_quantity']);
        $kanjia_quantity = 6;
        if ($kanjia_quantity <= 0 || $kanjia_quantity > 12) {
            $kanjia_quantity = 1;
        }

        //获取当前价格
        $current_price = intval(C('promotion_kanjia_price'));
        //获取该用户已有套餐
        $model_kanjia   = Model('p_kanjia');
        $current_kanjia = $model_kanjia->getQuotaCurrent($_SESSION['store_id']);
        $add_time       = 86400 * 30 * $kanjia_quantity;
        if (empty($current_kanjia)) {
            //生成套餐
            $param                = array();
            $param['member_id']   = $_SESSION['member_id'];
            $param['member_name'] = $_SESSION['member_name'];
            $param['store_id']    = $_SESSION['store_id'];
            $param['store_name']  = $_SESSION['store_name'];
            $param['start_time']  = TIMESTAMP;
            $param['end_time']    = TIMESTAMP + $add_time;
            $model_kanjia->addQuota($param);
        } else {
            $param             = array();
            $param['end_time'] = array('exp', 'end_time + ' . $add_time);
            $model_kanjia->editQuota($param, array('quota_id' => $current_kanjia['quota_id']));
        }

        //记录店铺费用
        $this->recordStoreCost($current_price * $kanjia_quantity, '购买砍价');

        $this->recordSellerLog('购买' . $kanjia_quantity . '份砍价套餐，单价' . $current_price . $lang['nc_yuan']);

        showDialog(Language::get('nc_common_save_succ'), self::LINK_LIST, 'succ');
    }

    /**
     * 选择活动商品
     **/
    public function goods_selectOp()
    {
        $model_goods             = Model('goods');
        $condition               = array();
        $condition['store_id']   = $_SESSION['store_id'];
        $condition['goods_name'] = array('like', '%' . $_GET['goods_name'] . '%');
        $goods_list              = $model_goods->getGeneralGoodsOnlineList($condition, '*', 10);

        Tpl::output('goods_list', $goods_list);
        Tpl::output('show_page', $model_goods->showpage());
        Tpl::showpage('store_promotion_kanjia.goods', 'null_layout');
    }

    /**
     * 商品添加
     **/
    public function kanjia_goods_addOp()
    {
        $goods_id     = intval($_POST['goods_id']);
        $kanjia_id    = intval($_POST['kanjia_id']);
        $kanjia_price = floatval($_POST['kanjia_price']);

        $model_goods  = Model('goods');
        $model_kanjia = Model('p_kanjia');

        $data           = array();
        $data['result'] = true;

        $goods_info = $model_goods->getGoodsInfoByID($goods_id);
        if (empty($goods_info) || $goods_info['store_id'] != $_SESSION['store_id']) {
            $data['result']  = false;
            $data['message'] = '参数错误';
            echo json_encode($data);
            die;
        }
        $condition              = array();
        $condition['store_id']  = $_SESSION['store_id'];
        $condition['kanjia_id'] = $kanjia_id;
        $kanjia_info            = $model_kanjia->getInfo($condition);
        if (!$kanjia_info) {
            $data['result']  = false;
            $data['message'] = '参数错误';
            echo json_encode($data);
            die;
        }

        //检查商品是否已经参加同时段活动
        $condition             = array();
        $condition['end_time'] = array('gt', $kanjia_info['start_time']);
        $condition['goods_id'] = $goods_id;
        $kanjia_goods          = $model_kanjia->getGoodsList($condition);
        if (!empty($kanjia_goods)) {
            $data['result']  = false;
            $data['message'] = '该商品已经参加了同时段活动';
            echo json_encode($data);
            die;
        }
        //检查商品是否已经参加拼团活动
        $condition     = array("goods_id" => $goods_id);
        $pintuan_goods = Model("p_pintuan")->getGoodsList($condition);
        if (!empty($pintuan_goods)) {
            $data['result']  = false;
            $data['message'] = '该商品已经参加了拼团活动';
            echo json_encode($data);
            die;
        }
        //检查商品是否已经参加限时折购活动
        $condition  = array("goods_id" => $goods_id);
        $time_goods = Model("p_time")->getGoodsList($condition);
        if (!empty($time_goods)) {
            $data['result']  = false;
            $data['message'] = '该商品已经参加了限时折购活动';
            echo json_encode($data);
            die;
        }

        //添加到活动商品表
        $param                   = array();
        $param['kanjia_id']      = $kanjia_info['kanjia_id'];
        $param['kanjia_name']    = $kanjia_info['kanjia_name'];
        $param['kanjia_title']   = $kanjia_info['kanjia_title'];
        $param['kanjia_explain'] = $kanjia_info['kanjia_explain'];
        $param['goods_id']       = $goods_info['goods_id'];
        $param['store_id']       = $goods_info['store_id'];
        $param['goods_name']     = $goods_info['goods_name'];
        $param['goods_price']    = $goods_info['goods_price'];
        $param['kanjia_price']   = $kanjia_price;
        $param['goods_image']    = $goods_info['goods_image'];
        $param['start_time']     = $kanjia_info['start_time'];
        $param['end_time']       = $kanjia_info['end_time'];
        $param['min_num']        = $kanjia_info['min_num'];
        $result                  = $model_kanjia->addGoods($param);
        if ($result) {
            $data['message']          = '添加成功';
            $param['kanjia_goods_id'] = $result;
            $param['goods_url']       = urlShop('goods', 'index', array('goods_id' => $param['goods_id']));
            $param['image_url']       = thumb($param, 240);
            $data['kanjia_goods']     = $param;
            $this->recordSellerLog('添加砍价商品，活动名称：' . $kanjia_info['kanjia_name'] . '，商品名称：' . $goods_info['goods_name']);
        } else {
            $data['result']  = false;
            $data['message'] = '参数错误';
        }
        echo json_encode($data);
        die;
    }

    /**
     * 商品价格修改
     **/
    public function kanjia_goods_price_editOp()
    {
        $kanjia_goods_id = intval($_POST['kanjia_goods_id']);
        $kanjia_price    = floatval($_POST['kanjia_price']);

        $data           = array();
        $data['result'] = true;

        $model_kanjia                 = Model('p_kanjia');
        $condition                    = array();
        $condition['store_id']        = $_SESSION['store_id'];
        $condition['kanjia_goods_id'] = $kanjia_goods_id;
        $kanjia_goods_info            = $model_kanjia->getGoodsInfo($condition);
        if (!$kanjia_goods_info) {
            $data['result']  = false;
            $data['message'] = '参数错误';
            echo json_encode($data);
            die;
        }

        $update                 = array();
        $update['kanjia_price'] = $kanjia_price;
        $result                 = $model_kanjia->editGoods($update, $condition);

        if ($result) {
            $kanjia_goods_info['kanjia_price'] = $kanjia_price;
            $data['kanjia_price']              = $kanjia_goods_info['kanjia_price'];

            $this->recordSellerLog('价格修改为：' . $kanjia_goods_info['kanjia_price'] . '，商品名称：' . $kanjia_goods_info['goods_name']);
        } else {
            $data['result']  = false;
            $data['message'] = L('nc_common_op_succ');
        }
        echo json_encode($data);
        die;
    }

    /**
     * 商品删除
     **/
    public function kanjia_goods_deleteOp()
    {
        $model_kanjia = Model('p_kanjia');

        $data           = array();
        $data['result'] = true;

        $kanjia_goods_id              = intval($_POST['kanjia_goods_id']);
        $condition                    = array();
        $condition['store_id']        = $_SESSION['store_id'];
        $condition['kanjia_goods_id'] = $kanjia_goods_id;
        $kanjia_goods_info            = $model_kanjia->getGoodsInfo($condition);
        if (!$kanjia_goods_info) {
            $data['result']  = false;
            $data['message'] = '参数错误';
            echo json_encode($data);
            die;
        }

        if (!$model_kanjia->delGoods($condition)) {
            $data['result']  = false;
            $data['message'] = '删除失败';
            echo json_encode($data);
            die;
        }

        $this->recordSellerLog('删除砍价商品，活动名称：' . $kanjia_info['kanjia_name'] . '，商品名称：' . $kanjia_goods_info['goods_name']);
        echo json_encode($data);
        die;
    }

    /**
     * 小导航
     *
     * @param string $menu_type 导航类型
     * @param string $menu_key 当前导航的menu_key
     * @param array $array 附加菜单
     * @return
     */
    private function profile_menu($menu_key = '')
    {
        $menu_array = array(
            1 => array('menu_key' => 'kanjia_list', 'menu_name' => '活动列表', 'menu_url' => 'index.php?act=store_promotion_kanjia&op=kanjia_list'),
        );
        switch ($menu_key) {
            case 'kanjia_add':
                $menu_array[] = array('menu_key' => 'kanjia_add', 'menu_name' => '添加活动', 'menu_url' => 'index.php?act=store_promotion_kanjia&op=kanjia_add');
                break;
            case 'kanjia_edit':
                $menu_array[] = array('menu_key' => 'kanjia_edit', 'menu_name' => '编辑活动', 'menu_url' => 'javascript:;');
                break;
            case 'quota_add':
                $menu_array[] = array('menu_key' => 'kanjia_add', 'menu_name' => '购买套餐', 'menu_url' => 'index.php?act=store_promotion_kanjia&op=quota_add');
                break;
            case 'kanjia_manage':
                $menu_array[] = array('menu_key' => 'kanjia_manage', 'menu_name' => '商品管理', 'menu_url' => 'index.php?act=store_promotion_kanjia&op=kanjia_manage&kanjia_id=' . $_GET['kanjia_id']);
                break;
            case 'kanjia_manage_apply':
                $menu_array[] = array('menu_key' => 'kanjia_manage_apply', 'menu_name' => '参与活动', 'menu_url' => 'index.php?act=store_promotion_kanjia&op=kanjia_manage&kanjia_id=' . $_GET['kanjia_id']);
                break;
        }

        Tpl::output('member_menu', $menu_array);
        Tpl::output('menu_key', $menu_key);
    }
}
